package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Transactional
    @Override
    public boolean save(DishDto dishDto) {
        //完善数据对象
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setSort(0);
        dishDto.setStatus(1);

        //条用数据层添加菜品 获取添加后菜品添加主键id
        dishMapper.insert(dishDto);
        //遍历口味记录列表完善数据
        List<DishFlavor> dishFlavorList = dishDto.getFlavors().stream().map((dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            return dishFlavor;
        })).collect(Collectors.toList());

        dishFlavorMapper.save(dishFlavorList);

        //清除缓存
        //redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        Set keys=redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return true;


    }

    @Override
    public Page<DishDto> findPage2(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page, pageSize);
        List<DishDto> dishDtoList = dishMapper.findAll2(name);
        PageInfo<DishDto> pageInfo = new PageInfo<>(dishDtoList);

        Page<DishDto> pageObj = new Page<>();
        pageObj.setRecords(pageInfo.getList());
        pageObj.setTotal(pageInfo.getTotal());

        return pageObj;
    }

    @Override
    public DishDto findById(Long id) {
        return dishMapper.findById(id);
    }

    @Override

    public List<Dish> findByCategoryId(Long categoryId) {
        return dishMapper.findByCategoryId(categoryId);
    }


    // 根据类别和状态查询菜品列表List<DishDto>
    @Override
    public List<DishDto> findByCategoryId(Long categoryId, Integer status) {
        String key = "dish_" + categoryId + "_" + status;
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList == null) {
            List<Dish> dishList = dishMapper.findByCategoryIdAndStatus(categoryId, status);
            List<DishDto> disDtoList = dishList.stream().map((dish -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);

                List<DishFlavor> dishFlavorList = dishFlavorMapper.findByDishId(dishDto.getId());
                dishDto.setFlavors(dishFlavorList);

                return dishDto;
            })).collect(Collectors.toList());

            //将数据写入缓存
            redisTemplate.opsForValue().set(key, disDtoList);

        }
        return dishDtoList;

    }

    /**
     * 作用：修改菜品
     *
     * @param dishDto 页面传递过来的参数包含菜品与口味
     * @return
     */
    @Override
    @Transactional
    public boolean updateWithFlavor(DishDto dishDto) {
        //1. 补全修改时间
        dishDto.setUpdateTime(LocalDateTime.now());
        //2 修改菜品
        dishMapper.update(dishDto);

        //3. 删除该菜品的所有口味信息
        dishFlavorMapper.deleteByDishId(dishDto.getId());

        //4. 补全口味信息，然后重新插入
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> dishFlavorList = flavors.stream().map((flavor -> {
            //对每一个元素进行加工
            flavor.setDishId(dishDto.getId());
            flavor.setCreateTime(LocalDateTime.now());
            flavor.setUpdateTime(LocalDateTime.now());
            flavor.setCreateUser(dishDto.getCreateUser());
            flavor.setUpdateUser(dishDto.getUpdateUser());
            return flavor;
        })).collect(Collectors.toList());

        //4. 批量保存口味信息
        dishFlavorMapper.save(dishFlavorList);

        //清除缓存
        Set keys=redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return true;
    }
}
